<template>
  <a-card :bordered="false">
    <div style="position: relative">
      <div id="container" style="z-index: 100"></div>
      <!-- 查询区域 -->
      <div class="edit-wrap">
        <div class="table-page-search-wrapper">
          <a-button type="success" @click="getTempData" style="margin: 0 10px">刷新</a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
            style="margin: 0 10px"
          >
            <a-button type="primary" icon="import">导点</a-button>
          </a-upload>
          <a-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl2"
            @change="handleImportExcel"
            style="margin: 0 10px"
          >
            <a-button type="primary" icon="import">导线</a-button>
          </a-upload>
          <a-popconfirm title="确定同步到正式表中吗?" @confirm="() => handleUpgradeData()">
            <a-button type="primary" style="margin: 0 10px">同步</a-button>
          </a-popconfirm>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteAllData()">
            <a-button type="danger" style="margin: 0 10px">删除</a-button>
          </a-popconfirm>
        </div>
      </div>
    </div>
    <!-- 弹窗信息展示模块 -->
    <div v-show="false">
      <LineInfoWindow
        ref="lineInfo"
        :info-line="infoLine"
        :facility-list="facilityList"
        @closeInfoWindow="closeInfoWindow"
      />
      <EquipInfoWindow
        ref="infoWindow"
        :info-obj="infoObj"
        :bj-info="bjInfo"
        @closeInfoWindow="closeInfoWindow"
        @updateInfoObj="handleUpdateInfoObj"
      />
    </div>
  </a-card>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getEquPolice } from '@/api/dashboard'
import { httpAction, getAction } from '@/api/manage'
import { wgs84togcj02 } from '@/utils/coordtransform'

import LineInfoWindow from './modules/PipLineTemp/line-info-window.vue'
import EquipInfoWindow from './modules/PipLineTemp/equip-info-window.vue'
let equipMarks = [] // marker
let markers = []
export default {
  name: 'PipLineTempList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    LineInfoWindow,
    EquipInfoWindow,
  },
  data() {
    return {
      description: '临时管点表管理页面',
      url: {
        list: '/ps/pipLineTemp/list',
        delete: '/ps/pipLineTemp/delete',
        deleteBatch: '/ps/pipLineTemp/deleteBatch',
        exportXlsUrl: '/ps/pipLineTemp/exportXls',
        importExcelUrl: 'paishui/tempData/tempPoint',
        importExcelUrl2: 'paishui/tempData/tempLine',
      },
      dictOptions: {},
      superFieldList: [],
      pointList: [],
      piplineList: [],
      showWushuiPip: true,
      showYushuiPip: true,
      yvshuiPipLineMarkerList: [],
      wvshuiPipLineMarkerList: [],
      lines: {},
      infoLine: {},
      facilityList: [],
      bjInfo: [], // marker-window 报警信息
      infoObj: {
        name: '',
      }, // marker-window 管点信息或设备信息
      disableMixinCreated: true,
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    importExcelUrl2: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl2}`
    },
  },
  created() {
    this.getSuperFieldList()
  },
  mounted() {
    this.initMap()
  },
  methods: {
    async getTempData() {
      const [resPoint, resYsLine, resWsLine] = await Promise.all([
        getAction('/paishui/tempData/query/point', { pageNo: 1, PageSize: 999999 }),
        getAction('/paishui/tempData/query/line/1', { pageNo: 1, PageSize: 999999 }),
        getAction('/paishui/tempData/query/line/2', { pageNo: 1, PageSize: 999999 }),
      ])
      if (!resPoint.result.length && !(resYsLine.result.length || resWsLine.result.length)) {
        this.$message.warning('暂无临时点线数据')
        return
      } else {
        if (resPoint.result.length) {
          this.initPointMark(resPoint.result)
        }
        if (resYsLine.result.length) {
          this.yvshuiPipLineMarkerList = resYsLine.result.map((line) => {
            return {
              path: line.map((point) => wgs84togcj02(point.longitude, point.latitude)),
              pipPointNos: [line[0].pipPointNo, line[line.length - 1].pipPointNo],
            }
          })
          this.levelChange(true, 1, '雨水管', '#00D3FF')
        }
        if (resWsLine.result.length) {
          this.wvshuiPipLineMarkerList = resWsLine.result.map((line) => {
            return {
              path: line.map((point) => wgs84togcj02(point.longitude, point.latitude)),
              pipPointNos: [line[0].pipPointNo, line[line.length - 1].pipPointNo],
            }
          })
          this.levelChange(true, 2, '污水管', '#F74020')
        }
      }
    },
    async handleUpgradeData() {
      const res = await httpAction('/paishui/tempData/sync', {}, 'put')
      if (res.success) {
        this.$message.success('正在同步数据中...,请等待一会儿')
      } else {
        this.$message.warning(res.message)
      }
    },
    async handleDeleteAllData() {
      const res = await httpAction('/paishui/tempData/del', {}, 'DELETE')
      if (res.success) {
        this.$message.success('已成功删除数据')
      }
    },
    // 初始化地图
    initMap() {
      AMapLoader.load({
        key: '7bf1afe0a111e75bc96b5f5d0553b5f3', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.MapType'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: '1.1', // AMapUI 缺省 1.1
          plugins: ['misc/PathSimplifier'], // 需要加载的 AMapUI ui插件
        },
      })
        .then((AMap) => {
          this.map = new AMap.Map('container', {
            //设置地图容器id
            // resizeEnable: true,
            viewMode: '3D', //是否为3D地图模式
            zoom: 12, //设置地图的缩放级别
            center: [119.646354, 29.129608], //初始化地图中心点位置
            mapStyle: 'amap://styles/3efe3caae4d86d89083fd8e4e911a826', //'amap://styles/macaron' // 设置地图的显示样式
          })
          this.map.addControl(new AMap.MapType({ defaultType: 1 }))
          this.getTempData()
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 管点切换设备弹窗信息的展示设备信息
    handleUpdateInfoObj(newData) {
      this.infoObj = { ...this.infoObj, ...newData }
    },
    initPointMark(pipList) {
      this.removePipMarkers()
      this.layerPoints = new AMap.LabelsLayer({
        // zooms: [3, 23],
        zIndex: 200,
        collision: false,
      })
      // 将图层添加到地图
      this.map.add(this.layerPoints)
      const pipPointList = pipList.map((item) => {
        // 处理管点经纬度 84to2000
        var curPosition = wgs84togcj02(item.longitude, item.latitude)
        item.lnglat = [...curPosition]
        // 判断显示管点icon的路径
        // item.pipType
        const iconName = this.parsePipPonitMarkerIconUrl(item)
        let iconUrl = require(`@/assets/amap/${iconName}`)
        let size = [12, 12]
        if (item.equNo) {
          size = [24, 30]
        }
        // let marker = new AMap.Marker({
        //   position: curPosition,
        //   extData: {
        //     item
        //   },
        //   cursor: 'pointer',
        //   icon: new AMap.Icon({
        //     image: iconUrl,
        //     size: size, //图标大小
        //     imageSize: size
        //   }),
        //   offset: new AMap.Pixel(-size[0] / 2, -size[1] / 2),
        //   zIndex: 100
        // })
        // marker.on('click', e => {
        //   console.log('管点信息-->', e.target.getExtData().item)
        //   this.markerClick(e.target.getExtData().item, e.lnglat)
        // })
        // 向全局equipMarks添加报警标记
        // equipMarks.push(marker)

        var curData = {
          position: curPosition,
          extData: {
            item,
          },
          cursor: 'pointer',
          icon: {
            type: 'image',
            image: iconUrl,
            size: size,
            anchor: 'bottom-center',
          },
          offset: new AMap.Pixel(0, -10),
        }
        var labelMarker = new AMap.LabelMarker(curData)
        // labelMarker.setExtData({item: item});
        markers.push(labelMarker)
        labelMarker.on('click', (e) => {
          this.markerClick(e.target.getExtData().item, e.lnglat)
        })
        return item
      })
      // this.initLabelsLayerSbxx()
      // 一次性将海量点添加到图层
      this.layerPoints.add(markers)

      // 将地图移动到适配图层
      this.map.setFitView(markers)
    },
    parsePipPonitMarkerIconUrl(item) {
      let icon = ''
      let showOtherEquip = item.showOtherEquip
      if (item.equNo) {
        // 有设备显示
        switch (item.pipType) {
          case 1:
            // 雨水井有设备
            if (item.policeStatus == '0') {
              icon = showOtherEquip ? 'Yshebeis_b.png' : 'Yshebei_b.png'
            } else {
              icon = showOtherEquip ? 'Yshebeis.png' : 'Yshebei.png'
            }
            break
          case 2:
            // icon = '污水井'
            if (item.policeStatus == '0') {
              icon = showOtherEquip ? 'Wshebeis_b.png' : 'Wshebei_b.png'
            } else {
              icon = showOtherEquip ? 'Wshebeis.png' : 'Wshebei.png'
            }
            break
          default:
            icon = showOtherEquip ? 'Wshebeis.png' : 'Wshebei.png'
            break
        }
      } else {
        switch (item.pipType) {
          case 1:
            icon = 'ysj.png'
            break
          case 2:
            icon = 'wsj.png'
            break
          default:
            icon = 'wsj.png'
            break
        }
      }
      return icon
    },
    markerClick(item, position) {
      // console.log('pipData', pipData)
      this.infoObj = item || {}
      // 因为组件无法及时渲染更新数据所以需要在nextTick中获取含有数据的弹窗信息
      this.$nextTick(() => {
        const content = this.$refs.infoWindow.$el
        let infoWindowData = new AMap.InfoWindow({
          isCustom: true, //使用自定义窗体
          content,
          offset: new AMap.Pixel(0, -10),
          autoMove: true,
        })
        this.openInfoWindow(infoWindowData, position)
        this.$refs.infoWindow.handleGetEchartDataList()
        this.getInfoWindowPolice(item.equNo)
      })
    },
    // 获取设备弹窗报警信息
    async getInfoWindowPolice(item) {
      const res = await getEquPolice(item)
      this.bjInfo = res.result ? res.result.records : []
    },
    removePipMarkers() {
      if (equipMarks.length) {
        this.map.remove(equipMarks)
        equipMarks = []
        this.layerPoints = null
      }
    },
    async initLabelsLayerSbxx() {
      if (this.layerItem) return
      let layerName = 'layerItem'
      // console.log(layerName)
      this[layerName] = new AMap.LabelsLayer({
        zooms: [3, 23],
        zIndex: 100,
        collision: false,
      })
      // 将图层添加到地图
      this.map.add(this[layerName])
      this.map.add(equipMarks)
      this.map.setFitView(equipMarks)
    },
    removeEquipMarkers() {
      if (equipMarks.length) {
        this.map.remove(equipMarks)
        equipMarks = []
      }
    },
    levelChange(flag, type, lineName, color) {
      if (flag) {
        const makerList = type === 1 ? this.yvshuiPipLineMarkerList : this.wvshuiPipLineMarkerList
        this.addmanyPolyline(makerList, lineName, color)
      } else {
        this.removeLine(lineName)
      }
    },
    addmanyPolyline(makerList, lineName, color) {
      if (makerList.length == 0) return
      AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifier) => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！')
          return
        }
        //创建组件实例
        this.lines[lineName] = new PathSimplifier({
          zIndex: 100,
          map: this.map, //所属的地图实例
          getPath: function (pathData) {
            return pathData.path
          },
          getHoverTitle: function () {
            return ''
          },
          renderOptions: {
            //线的样式
            pathLineStyle: {
              strokeStyle: color,
              lineWidth: 2,
              borderStyle: color,
              borderWidth: 0,
              dirArrowStyle: true,
            },
            pathLineHoverStyle: {
              strokeStyle: color,
              lineWidth: 4,
              borderStyle: color,
              borderWidth: 0,
              dirArrowStyle: true,
            },
            startPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0,
            },
            endPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0,
            },
            keyPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0,
            },
          },
          clickToSelectPath: false,
        })
        //构建轨迹
        this.lines[lineName].setData(makerList)
        // // 管道点击显示管道信息弹窗
        this.lines[lineName].on('pathClick', (e, { pathData }) => {
          console.log('管道信息-->', pathData)
          this.getLineInfo(pathData.pipPointNos[0], pathData.pipPointNos[1], [
            e.originalEvent.lnglat.lng,
            e.originalEvent.lnglat.lat,
          ])
        })
      })
    },
    // 管线被点击，获取对应管线信息并弹窗展示处理
    getLineInfo(startPoint, endPoint, position) {
      this.getpipInfo(startPoint, endPoint)
      this.openLineInfoWin(position)
    },
    // 请求获取管线pipPath信息
    async getpipInfo(startPointNo, endPointNo) {
      // const res = await getAction('/paishui/paishuiPip/queryByPoint', {
      const res = await getAction('/paishui/tempData/query/ByPoint', {
        ed: endPointNo,
        st: startPointNo,
      })
      const infoLine = res.result
      this.infoLine = infoLine
      // console.log('infoLine', infoLine)
      if (infoLine.facilityId) {
        // 获取污水设备列表
        this.getfacilityList()
      }
    },
    async getfacilityList() {
      const res = await getAction(`/paishui/paishuiFacility/list`, { pageNo: 1, pageSize: 10000 })
      if (res.code !== 200) {
        return
      }
      const facilityList = res.result.records || []
      this.facilityList = facilityList
        .filter((facility) => facility.facilityType === 1)
        .map((facility) => ({
          value: facility.id,
          label: facility.facilityName,
        }))
    },
    // 在地图点位上展示管线信息弹窗
    openLineInfoWin(position) {
      let infoWindowData = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: this.$refs.lineInfo.$el,
        offset: new AMap.Pixel(0, -20),
        autoMove: true,
      })
      this.openInfoWindow(infoWindowData, position)
    },
    // 展示地图弹窗并设置地图中心点
    openInfoWindow(infoWindow, position) {
      // console.log(position)
      infoWindow.open(this.map, position)
      this.map.setCenter(position)
    },
    //关闭窗体
    closeInfoWindow() {
      console.log('关闭窗体')
      this.map.clearInfoWindow()
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'int', value: 'version', text: '版本号', dictCode: '' })
      fieldList.push({ type: 'int', value: 'deleted', text: '是否删除', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pipName', text: '管点名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pipNo', text: '管点编号', dictCode: '' })
      fieldList.push({ type: 'int', value: 'pipType', text: '管点类型 1雨水井 2污水井', dictCode: '' })
      fieldList.push({ type: 'string', value: 'associationPosPointNo', text: '关联点位编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'dsm', text: '地面高程', dictCode: '' })
      fieldList.push({ type: 'string', value: 'arcgis', text: 'ArcGis编号', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'longitude', text: '经度', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'latitude', text: '纬度', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'geophysicaLongitude', text: '物探经度', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'geophysicaLatitude', text: '物探纬度', dictCode: '' })
      fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
      fieldList.push({ type: 'int', value: 'status', text: '状态', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaName', text: '所属区域', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaId', text: '所属区域id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'associationPosPoint', text: '关联点位id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'street', text: '道路', dictCode: '' })
      fieldList.push({ type: 'string', value: 'address', text: '地址', dictCode: '' })
      fieldList.push({ type: 'string', value: 'measureDepth', text: '井深', dictCode: '' })
      fieldList.push({ type: 'int', value: 'isTerminal', text: '是否终端', dictCode: '' })
      fieldList.push({ type: 'int', value: 'pipPointDefective', text: '管点缺陷', dictCode: '' })
      fieldList.push({ type: 'string', value: 'manageScope', text: 'null', dictCode: '' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
#container {
  width: 1420px;
  height: 1158px;
}
.edit-wrap {
  position: absolute;
  top: 10px;
  left: 0;
  z-index: 100;
}
</style>
